﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace InSTEDD.Labs.Geo.Locators
{
	public class CountryLocator
	{
		public Dictionary<string, Country> Countries = new Dictionary<string, Country>();


		public static CountryLocator FromFile(string relativePath)
		{
			CountryLocator locator = new CountryLocator();

			string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativePath);
			StreamReader reader = new StreamReader(fullPath);
			while (!reader.EndOfStream)
			{
				string countryName = reader.ReadLine();
				string countryPolygonString = reader.ReadLine();
				string dumbdata = reader.ReadLine();

				Polygon countryPolygon = PolygonBuilder.FromKMLString(countryPolygonString);

				Country country;
				if (!locator.Countries.ContainsKey(countryName))
				{
					country = new Country(countryName);
					locator.Countries.Add(countryName, country);
				}
				else
					country = locator.Countries[countryName];

				country.Areas.Add(countryPolygon);
			}
			return locator;
		}

		public Country GetCountryForPoint(PPoint test)
		{
			var query = from country in this.Countries.Values.AsEnumerable()
						where country.Contains(test)
						select country;

			return query.FirstOrDefault();
		}
	}
}
